package cn.wolfcode.web.controller;


import cn.wolfcode.anno.RequiredPermission;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;


    @RequestMapping("/list")
    @RequiredPermission(name = "角色查询", expression = "role:list")
    public String list(QueryObject qo, Model model){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list";
    }

    @RequestMapping("/delete")
    @RequiredPermission(name = "角色删除", expression = "role:delete")
    public String delete(Long id){
        roleService.delete(id);
        return "redirect:/role/list";
    }

    @RequestMapping("/input")
    @RequiredPermission(name = "角色新增/编辑", expression = "role:saveOrUpdate")
    public String input(Long id, Model model){
        // ====== 用于显示左边下拉框所有的 "权限" =======
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions", permissions);

        if (id != null){ // 编辑
            Role role = roleService.selectOne(id);
            model.addAttribute("role",role);

            // =========编辑时 用于显示右边下拉框拥有的 “权限” =========
            List<Permission> oewPermissions = permissionService.selectPermissionById(id);
            model.addAttribute("oewPermissions",oewPermissions);

            // ========去除左边重复的可选择权限========
            permissions.removeAll(oewPermissions);
        }
        return "role/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "角色新增/编辑", expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] permissionIds){
        if (role.getId() != null){  // 修改
            roleService.update(role,permissionIds);
        }else { // 新增
            roleService.insert(role, permissionIds);
        }
        return "redirect:/role/list";
    }

}
